package com.dwjm.exam.admin;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/profile")
public class AdminProfileHandler extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");

        // 从请求中获取管理员ID
        String adminIdStr = req.getParameter("adminId");
        int adminId = 0;
        
        try {
            if (adminIdStr != null && !adminIdStr.isEmpty()) {
                adminId = Integer.parseInt(adminIdStr);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        
        AdminDaoImpl adminDao = new AdminDaoImpl();
        Admin admin = null;
        
        if (adminId > 0) {
            // 如果指定了ID，则查询该管理员
            admin = adminDao.getAdminById(adminId);
        }
        
        PrintWriter out = resp.getWriter();
        Map<String, Object> responseMap = new HashMap<>();
        
        if (admin != null) {
            // 构建响应数据，不返回密码
            Map<String, Object> adminData = new HashMap<>();
            adminData.put("adminId", admin.getAdminId());
            adminData.put("username", admin.getUsername());
            adminData.put("realName", admin.getRealName());
            adminData.put("email", admin.getEmail());
            adminData.put("phone", admin.getPhone());
            adminData.put("role", admin.getRole());
            adminData.put("createTime", admin.getCreateTime() != null ? admin.getCreateTime().getTime() : null);
            adminData.put("lastLoginTime", admin.getLastLoginTime() != null ? admin.getLastLoginTime().getTime() : null);
            adminData.put("status", admin.getStatus());
            
            responseMap.put("code", 200);
            responseMap.put("msg", "获取管理员信息成功");
            responseMap.put("data", adminData);
        } else {
            responseMap.put("code", 400);
            responseMap.put("msg", "未找到管理员信息");
        }
        
        // 转换为JSON并输出
        Gson gson = new Gson();
        String json = gson.toJson(responseMap);
        out.write(json);
        out.flush();
        out.close();
    }
} 